package com.soft.sitegenerator.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.soft.sitegenerator.Component;
import com.soft.sitegenerator.DataBaseComponent;
import com.soft.sitegenerator.business.hibernate.SimpleTemplate;
import com.soft.sitegenerator.business.hibernate.Template;
import com.soft.sitegenerator.exceptions.ObjectNotFoundException;
import com.soft.sitegenerator.form.TemplateEditForm;

public class TemplateEditAction extends DispatchAction {

	public ActionForward editTemplate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		TemplateEditForm templateEditForm = (TemplateEditForm) form;

		Long id = new Long(Long.parseLong(request.getParameter("id")));

		Template template = templateEditForm.getTemplate();
		template.setId(id);

		try {
			template.load();
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}

		return mapping.findForward("showEdit");
	}

	public ActionForward updateTemplate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		TemplateEditForm templateEditForm = (TemplateEditForm) form;

		Component component = new DataBaseComponent();
		SimpleTemplate template = (SimpleTemplate) component.getBean("simpleTemplatesHib");
		template.setId(templateEditForm.getId());

		try {
			template.load();
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}

		template.setText(templateEditForm.getText());
		template.update();

		return mapping.findForward("showList");

	}

}
